package cn.touna.jss.modules.third.moxie;

import cn.touna.risk.api.contraints.facet.First;
import cn.touna.risk.api.contraints.facet.Second;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.risk.api.utils.JSONUtil;
import cn.touna.jss.common.properties.disconf.MoXieProperties;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.moxie.entity.MoXieEntity;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.exception.BusinessException;
import cn.touna.risk.api.exception.ServiceException;
import cn.touna.risk.api.http.HttpsUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 魔蝎
 * Created by wuwc on 2017/12/13.
 */
@Service
public class MoXieService {

    private static final Logger LOGGER = LogManager.getLogger(MoXieService.class);

    @Autowired
    private MoXieProperties moXieProperties;

    @ApiMapping(value = "moxie.securityReport",useCache = false,desc = "魔蝎.社保报告")
    public Response securityReport(MoXieEntity moXieEntity) {
        Response response = new Response();
        ValidUtil.checkRequestParams(moXieEntity, First.class);
        try {
            String resut = queryData(moXieProperties.getSecurityUrl(), moXieEntity.getTask_id());
            LOGGER.info("RSP【社保查询返回】，result:{}", resut);
            String code = JSONUtil.getString(resut, "code", null);
            if (StringUtils.isBlank(code)) {
                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR, JSONUtil.getString(resut, "detail", ""));
            }
            return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, resut);
        } catch (Exception e) {
            LOGGER.error("调用【社保查询】异常,task_id:{},msg:{}", moXieEntity.getTask_id(), e.getMessage());
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
        }
    }

    @ApiMapping(value = "moxie.fundReport",useCache = false,desc = "魔蝎.公积金报告")
    public Response fundReport(MoXieEntity moXieEntity) {
        Response response = new Response();
        ValidUtil.checkRequestParams(moXieEntity, First.class);
        try {
            String resut = queryData(moXieProperties.getFundUrl(), moXieEntity.getTask_id());
            LOGGER.info("RSP【公积金查询返回】，result:{}", resut);
            String code = JSONUtil.getString(resut, "code", null);
            if (StringUtils.isBlank(code)) {
                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR, JSONUtil.getString(resut, "detail", ""));
            }
            return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, resut);
        } catch (Exception e) {
            LOGGER.error("调用【公积金查询】异常,task_id:{},msg:{}", moXieEntity.getTask_id(), e.getMessage());
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
        }
    }

    @ApiMapping(value = "moxie.zhengXinReport",desc = "魔蝎.人行征信")
    public Response zhengXinReport(MoXieEntity moXieEntity) {
        Response response = new Response();
        ValidUtil.checkRequestParams(moXieEntity, First.class);
        try {
            Map<String, String> headMap = getAuthorization();

            String resut = queryData(moXieProperties.getZhengxinUrl(), moXieEntity.getTask_id());
            return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, resut);
        } catch (Exception e) {
            LOGGER.error("调用【人行征信查询】异常,task_id:{},msg:{}", moXieEntity.getTask_id(), e.getMessage());
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
        }
    }

    @ApiMapping(value = "moxie.mailReport",useCache = false,desc = "魔蝎.信用卡邮箱")
    public Response mailReport(MoXieEntity moXieEntity) throws BusinessException {
        Response response = new Response();
        ValidUtil.checkRequestParams(moXieEntity, First.class, Second.class);
        try {
            String resut = queryData(moXieProperties.getEmailUrl(), moXieEntity.getEmail_id(), moXieEntity.getTask_id());
            if (JSONUtil.isJsonObject(resut)) {
                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR, JSONUtil.getString(resut, "detail", ""));
            }
            return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, resut);
        } catch (Exception e) {
            LOGGER.error("调用【信用卡邮箱查询返回】异常,task_id:{},msg:{}", moXieEntity.getTask_id(), e.getMessage());
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
        }
    }

    @ApiMapping(value = "moxie.securityBill",useCache = false,desc = "魔蝎.社保账单")
    public Response securityBill(MoXieEntity moXieEntity) {
        Response response = new Response();
        ValidUtil.checkRequestParams(moXieEntity, First.class);
        try {
            String resut = queryData(moXieProperties.getOriginSecurityUrl(), moXieEntity.getTask_id());
            LOGGER.info("RSP【社保账单查询返回】，result:{}", resut);
            String task_id = JSONUtil.getString(resut, "task_id", null);
            if (StringUtils.isBlank(task_id)) {
                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR, JSONUtil.getString(resut, "detail", ""));
            }
            return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, resut);
        } catch (Exception e) {
            LOGGER.error("调用【社保原始报告查询】异常,task_id:{},msg:{}", moXieEntity.getTask_id(), e.getMessage());
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
        }
    }

    @ApiMapping(value = "moxie.fundBill",useCache = false,desc = "魔蝎.公积金账单")
    public Response fundBill(MoXieEntity moXieEntity) {
        Response response = new Response();
        ValidUtil.checkRequestParams(moXieEntity, First.class);
        try {
            String resut = queryData(moXieProperties.getOriginFundUrl(), moXieEntity.getTask_id());
            LOGGER.info("RSP【公积金账单查询返回】，result:{}", resut);
            String task_id = JSONUtil.getString(resut, "task_id", null);
            if (StringUtils.isBlank(task_id)) {
                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR, JSONUtil.getString(resut, "detail", ""));
            }
            return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, resut);
        } catch (Exception e) {
            LOGGER.error("调用【公积金账单查询】异常,task_id:{},msg:{}", moXieEntity.getTask_id(), e.getMessage());
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
        }
    }

    @ApiMapping(value = "moxie.mailBill",useCache = false,desc = "魔蝎.信用卡邮箱账单")
    public Response mailBill(MoXieEntity moXieEntity) {
        Response response = new Response();
        ValidUtil.checkRequestParams(moXieEntity, First.class);
        try {
            Map<String, String> headMap = getAuthorization();
            Map<String, String> bodyMap = new HashMap<>();
            bodyMap.put("task_id", moXieEntity.getTask_id());
            String resut = HttpsUtil.getInstance().get(moXieProperties.getOriginEmailUrl(), bodyMap, headMap);
            LOGGER.info("RSP【信用卡邮箱账单查询返回】，result:{}", resut);
            String size = JSONUtil.getString(resut, "size", null);
            if (StringUtils.isBlank(size)) {
                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR, JSONUtil.getString(resut, "detail", ""));
            }
            return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, resut);
        } catch (Exception e) {
            LOGGER.error("调用【信用卡邮箱账单查询】异常,task_id:{},msg:{}", moXieEntity.getTask_id(), e.getMessage());
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
        }
    }


    private String queryData(String url, String... ids) throws Exception {
        Map<String, String> headMap = getAuthorization();
        String requestUrl = getRequestUrl(url, ids);
        return HttpsUtil.getInstance().getWithHead(requestUrl, headMap);
    }

    private String getRequestUrl(String url, String... ids) {
        if (StringUtils.isBlank(url)) {
            throw new ServiceException(ids + ",无效的URL");
        }
        StringBuilder sBuilder = new StringBuilder();
        sBuilder.append(url).append("/");
        for (String id : ids) {
            sBuilder.append(id).append("/");
        }
        return sBuilder.toString();
    }

    private Map<String, String> getAuthorization() {
        Map<String, String> headerMap = new HashMap<>();
        StringBuilder sBuilder = new StringBuilder();

        sBuilder.append("token").append(" ").append(moXieProperties.getToken());
        headerMap.put("Authorization", sBuilder.toString());
        return headerMap;
    }
}
